package com.taiji.dicom4cloud.smart.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taiji.dicom4cloud.common.model.entity.SysDept;
import com.taiji.dicom4cloud.smart.dao.OrgMapper;
import com.taiji.dicom4cloud.smart.model.entity.Org;
import com.taiji.dicom4cloud.smart.service.OrgService;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrgServiceImpI extends ServiceImpl<OrgMapper, Org> implements OrgService {

    @Override
    public List<Tree<Integer>> listOrgTrees() {
        return getOrgTree(this.list(Wrappers.emptyWrapper()));
    }


    private List<Tree<Integer>> getOrgTree(List<Org> orgs) {
        List<TreeNode<Integer>> collect = orgs.stream()
                .filter(org -> org.getOrgId().intValue() != org.getParentId())
                .sorted(Comparator.comparingInt(Org::getSort)).map(dept -> {
                    TreeNode<Integer> treeNode = new TreeNode();
                    treeNode.setId(dept.getOrgId());
                    treeNode.setParentId(dept.getParentId());
                    treeNode.setName(dept.getOrgName());
                    return treeNode;
                }).collect(Collectors.toList());

        return TreeUtil.build(collect, 0);
    }
}
